package com.zxbit.flash.ui.activity.loan;

import android.annotation.SuppressLint;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.Gson;
import com.zxbit.flash.R;
import com.zxbit.flash.cache.Acache;
import com.zxbit.flash.cache.AcacheKeys;
import com.zxbit.flash.adapter.ProductTermAdapter;
import com.zxbit.flash.adapter.ProductTermAdapter.OnItemClickListener;
import com.zxbit.flash.base.BaseTitleActivity;
import com.zxbit.flash.common.AuthRouter;
import com.zxbit.flash.common.Constant;
import com.zxbit.flash.common.RouterMap;
import com.zxbit.flash.common.UserInfo;
import com.zxbit.flash.mvpview.AuthMvpView;
import com.zxbit.flash.mvpview.CalculateMvpView;
import com.zxbit.flash.mvpview.OrderMvpView;
import com.zxbit.flash.network.Urls;
import com.zxbit.flash.permission.IPermisson;
import com.zxbit.flash.permission.Permission;
import com.zxbit.flash.presenter.AuthPresenter;
import com.zxbit.flash.presenter.CalculatePresenter;
import com.zxbit.flash.presenter.OrderPresenter;
import com.zxbit.flash.bean.AuthData;
import com.zxbit.flash.response.AuthResponse;
import com.zxbit.flash.bean.CalculateData;
import com.zxbit.flash.response.CalculateResponse;
import com.zxbit.flash.response.CheckOrderResponse;
import com.zxbit.flash.response.CreateOrderResponse;
import com.zxbit.flash.bean.JsOrderData;
import com.zxbit.flash.bean.ProductItemData;
import com.zxbit.flash.bean.ProductListData;
import com.zxbit.flash.response.UserInformationResponse;
import com.zxbit.flash.utils.LocationUtils;
import com.zxbit.flash.utils.NoDoubleClickUtils;
import com.zxbit.flash.utils.StringUtils;
import com.zxbit.flash.utils.ToastUtils;
import com.zxbit.flash.utils.toolutil.MathUtil;

import java.util.ArrayList;
import java.util.Collections;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

/**
 * 借款详细信息的
 */
@Route(name = "借款信息", path = RouterMap.LOANPAGE)
public class LoanActivity extends BaseTitleActivity implements IPermisson, OnItemClickListener,
        CalculateMvpView, AuthMvpView, OrderMvpView {

    @BindView(R.id.tv_product_range)
    TextView tvProductRange; // Money
    @BindView(R.id.recycler_product_term)
    RecyclerView recyclerProductTerm;
    @BindView(R.id.tv_data_empty)
    TextView tvDataEmpty;
    @BindView(R.id.layout_loan_detail)
    LinearLayout layoutLoanDetail; // 详情布局
    @BindView(R.id.tv_interest)
    TextView tvInterest; // 利息
    @BindView(R.id.tv_member_fee)
    TextView tvMemberFee; // 会员管理费
    @BindView(R.id.tv_account_fee)
    TextView tvAccountFee; // 账户管理费
    @BindView(R.id.tv_time_out)
    TextView tvTimeOut; // 到期应还
    @BindView(R.id.tv_real_pay)
    TextView tvRealPay; // 实收
    @BindView(R.id.check_agreement)
    CheckBox checkAgreement;
    @BindView(R.id.tv_text_agreement)
    TextView tv_Agreement;
    @Autowired(name = Constant.LOAN_TERM_LIST)
    ProductListData productListData; // 传递过来的 mBorrowMoney mPid用来赋值

    private CalculatePresenter calculatePresenter;
    private AuthPresenter authPresenter;
    private OrderPresenter orderPresenter;
    private ProductTermAdapter productTermAdapter;
    private String mPid;
    private ArrayList<CalculateData> mCalculateList; // 当前明细列表

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
    }

    @Override
    protected void onUIReady() {
        calculatePresenter = new CalculatePresenter(this);
        authPresenter = new AuthPresenter(this);
        orderPresenter = new OrderPresenter(this);
        if (productListData == null || productListData.getpList() == null || productListData.getpList().size() < 1) {
            ToastUtils.showShort(this, getStringResource(R.string.incorrect_parameters));
            finish();
            return;
        }
        ArrayList<ProductItemData> productItemTermList = productListData.getpList();
        Collections.sort(productItemTermList);
        // 默认选中可借产品
        for (int i = 0; i < productItemTermList.size(); i++) {
            if (!"1".equals(productItemTermList.get(i).getLendStatus())) {
                ProductItemData productItemData = productItemTermList.get(i);
                getProductTermAdapter().setSelect(i);
                mPid = productItemData.getPId();
                break;
            }
        }
        if (StringUtils.isEmpty(productListData.getpRange()) || StringUtils.isEmpty(mPid)) {
            ToastUtils.showShort(this, getStringResource(R.string.loan_level_too_low));
            finish();
            return;
        }
        tvProductRange.setText(StringUtils.getDotMoneyStr(productListData.getpRange()));
        recyclerProductTerm.setLayoutManager(new GridLayoutManager(this, 2));
        recyclerProductTerm.setAdapter(getProductTermAdapter());
        getProductTermAdapter().addItems(productItemTermList);

        calculatePresenter.getAllCalculateData(productItemTermList);
        showLoadingView();
    }

    private ProductTermAdapter getProductTermAdapter() {
        if (productTermAdapter == null) {
            productTermAdapter = new ProductTermAdapter(this, this);
        }
        return productTermAdapter;
    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_repayment;
    }

    @Override
    public String getPageTitle() {
        return getStringResource(R.string.loan_page_title);
    }

    @OnClick({R.id.tv_data_empty, R.id.tv_text_agreement, R.id.btn_modified_amount, R.id.btn_repayment_affirm})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_data_empty:
                if (productListData.getpList() == null || productListData.getpList().size() == 0)
                    return;
                calculatePresenter.getAllCalculateData(productListData.getpList());
                showLoadingView();
                break;
            case R.id.tv_text_agreement:
                checkAgreement.setChecked(!checkAgreement.isChecked());
                break;
            case R.id.btn_modified_amount:
                finish();
                break;
            case R.id.btn_repayment_affirm:
                if (NoDoubleClickUtils.isDoubleClick()) return;
                if (StringUtils.isEmpty(productListData.getpRange()) || StringUtils.isEmpty(mPid)) {
                    ToastUtils.showShort(this, getStringResource(R.string.incorrect_parameters));
                    return;
                }
                // 提单成功后上传位置信息
                Permission permission = new Permission(LoanActivity.this, LoanActivity.this);
                permission.uploadLocation();
                break;
        }
    }

    @OnCheckedChanged(R.id.check_agreement)
    public void OnCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            jumpToWebPage();
        }
    }

    @Override
    public void onItemClick(View view, int position, boolean lendStatus) {
        if (!lendStatus && mCalculateList != null && mCalculateList.size() > 0) {
            mPid = mCalculateList.get(position).getPId();
            fillLoanDetailView(mCalculateList.get(position));
        } else {
            ToastUtils.showShort(this, getResources().getString(R.string.loan_level_too_low));
        }
    }

    /**
     * 跳转借款协议
     */
    private void jumpToWebPage() {
        CalculateData calculateData = getSelectCalculateData();
        if (calculateData == null || StringUtils.isEmpty(productListData.getpRange())) {
            tvDataEmpty.setVisibility(View.VISIBLE);
            layoutLoanDetail.setVisibility(View.GONE);
            ToastUtils.showShort(this, getStringResource(R.string.loan_no_data));
            return;
        }

        JsOrderData orderData = new JsOrderData();
        orderData.setBorrowMoney(productListData.getpRange());
        orderData.setBorrowDay(calculateData.getPTerm());
        orderData.setToken(UserInfo.getToken());
        ARouter.getInstance().build(RouterMap.WEB_VIEW_PAGE)
                .withString(Constant.PARAMS_URL, Urls.REGISTER_CONTRACT_URL)
                .withParcelable(Constant.PARAMS_ORDER_DATA, orderData)
                .withInt(Constant.PARAMS_TYPE, Constant.WEB_TYPE_LOAN).navigation();
    }

    private CalculateData getSelectCalculateData() {
        if (StringUtils.isEmpty(mPid) || mCalculateList == null) return null;
        // 默认选中可借产品
        for (int i = 0; i < mCalculateList.size(); i++) {
            if (mPid.equals(mCalculateList.get(i).getPId())) {
                return mCalculateList.get(i);
            }
        }
        return null;
    }

    @Override
    public void onGetDataNext(CalculateResponse response) {
        dismissLoadingView();
        if (response.getStatus() == Constant.HTTP_OK) {
            if (response.hasData()) {
                tvDataEmpty.setVisibility(View.GONE);
                layoutLoanDetail.setVisibility(View.VISIBLE);
                mCalculateList = response.getData();
                Collections.sort(mCalculateList);
                fillLoanDetailView(getSelectCalculateData());
            } else {
                tvDataEmpty.setVisibility(View.VISIBLE);
                layoutLoanDetail.setVisibility(View.GONE);
            }
        } else {
            tvDataEmpty.setVisibility(View.VISIBLE);
            layoutLoanDetail.setVisibility(View.GONE);
            ToastUtils.showShort(this, response.getMessage());
        }
    }

    @SuppressLint({"StringFormatInvalid", "SetTextI18n"})
    private void fillLoanDetailView(CalculateData data) {
        if (data == null) return;
        String loanMoneyUnit = getResources().getString(R.string.loan_money_unit);

        tvInterest.setText(String.format(loanMoneyUnit, StringUtils.getDotMoneyStr
                (MathUtil.calculateMoney(productListData.getpRange(), data.getPInterest(), data.getPTerm()))));
        tvMemberFee.setText(String.format(loanMoneyUnit, StringUtils
                .getDotMoneyStr(MathUtil.calculateMoney(productListData.getpRange(), data.getPCreditserviceFee()
                        , data.getPTerm()))));
        tvAccountFee.setText(String.format(loanMoneyUnit, StringUtils
                .getDotMoneyStr(MathUtil.calculateMoney(productListData.getpRange(), data.getPAccountFee(), data
                        .getPTerm()))));
        tvTimeOut.setText(String.format(loanMoneyUnit, StringUtils.getDotMoneyStr(data.getExpiryReturned())));
        tvRealPay.setText(String.format(loanMoneyUnit, StringUtils.getDotMoneyStr(data.getNeteceipts())));
    }

    @Override
    public void onSuccess(int result) {
        orderPresenter.checkOrderQualifications();
        showLoadingView();
    }

    @Override
    public void onGetDataNext(CheckOrderResponse response) {
        // 检查是否可以提单
        if (response.getStatus() == Constant.HTTP_OK) {
            authPresenter.getAuthInfo();
        } else {
            dismissLoadingView();
            ToastUtils.showShort(this, response.getMessage());
        }
    }

    @Override
    public void onGetDataNext(AuthResponse response) {
        // 检查认证状态
        if (response.getStatus() == Constant.HTTP_OK) {
            if (response.hasData()) {
                // 我不知道这要缓存个啥
                Acache.get(this).put(AcacheKeys.AUTH, new Gson().toJson(response.getData(), AuthData.class));
                // 1未认证，2通过
                if (response.getData().getStatus() == Constant.AUTH_STATUS_PASS) {
                    orderPresenter.createOrder(productListData.getpRange(), mPid);
                } else {
                    dismissLoadingView();
                    // TODO:此处应该弹框询问用户是否认证
                    ToastUtils.showShort(this, R.string.auth_status_not_pass);
                    AuthRouter.getInstance().jump2FirstNotAuthPager();
                }
            } else {
                dismissLoadingView();
                ToastUtils.showShort(this, R.string.loan_no_data);
            }
        } else {
            dismissLoadingView();
            ToastUtils.showShort(this, response.getMessage());
        }
    }

    @Override
    public void onGetDataNext(CreateOrderResponse response) {
        // 提单
        if (response.getStatus() == Constant.HTTP_OK) {
            // 上报经纬度
            Location location = LocationUtils.getLocation(LoanActivity.this);
            if (location == null) {
                onGetDataNext();
            } else {
                orderPresenter.uploadLocation(location);
            }
        } else {
            dismissLoadingView();
            ToastUtils.showShort(this, response.getMessage());
        }
    }

    @Override
    public void onGetDataNext() {
        // 提交位置信息 且 跳转首页
        dismissLoadingView();
        ARouter.getInstance().build(RouterMap.STATUS_DISPLAY).withInt(Constant.PAGE_TYPE, Constant.STATUS_TYPE_BORROW).navigation();
        finish();
    }

    @Override
    public void onGetDataNext(UserInformationResponse response) {}

    @Override
    public void onGetDataError(Throwable throwable) {
//        tvDataEmpty.setVisibility(View.VISIBLE);
//        layoutLoanDetail.setVisibility(View.GONE);
        dismissLoadingView();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //保存销毁之前的数据
        outState.putParcelable(Constant.LOAN_TERM_LIST, productListData);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        productListData = savedInstanceState.getParcelable(Constant.LOAN_TERM_LIST);
    }
}
